﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DomainModel.Abstract;
using DomainModel.Concrete;
using DomainModel;
using DomainModel.JSON;
using DomainModel.Entities;
using System.Globalization;
using System.Threading;
using Common;

namespace OrdersSystem.Controllers
{
    public class OrdersController : Controller
    {

        private vUser CurrentUser;
       

        public OrdersController()
        {
              
        }

        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);
            CurrentUser = Repositories.VUserRepository.GetUser(this.User.Identity.Name);
            InitViewData();
        }

        private void InitViewData()
        {
            this.ViewData["Manager"] = !CurrentUser.IsClient?"1":string.Empty;

            if (this.ViewData["StatusList"] == null)
            {
                string s = string.Empty;
                IQueryable<Status> ss = Repositories.StatusRepository.Statuses;
                if (CurrentUser.IsClient)
                {
                    s = "1:Создан;2:Не обработан";
                }
                else
                {
                    foreach (Status st in ss)
                    {
                        s += string.Format("{0}:{1};", st.StatusID.ToString(), st.Name);
                    }
                }                
                this.ViewData["StatusList"] = s.TrimEnd(';');
            }
            if (!CurrentUser.IsClient)
            {
                if (this.ViewData["UserList"] == null)
                {
                    string s = string.Empty;
                    foreach (var u in Repositories.UserRepository.GetClients(CurrentUser.IsAdmin,CurrentUser.UserID))
                    {
                        s += string.Format("{0}:{1};", u.UserID.ToString(), string.Format("{0} {1}.{2}.", u.Surname, u.Name[0], u.Patro[0]));
                    }
                    this.ViewData["UserList"] = s.TrimEnd(';');
                }

                if (CurrentUser.IsAdmin)
                {
                    if (this.ViewData["ManagerList"] == null)
                    {
                        string s = string.Empty;
                        foreach (var u in Repositories.UserRepository.GetManagers())
                        {
                            s += string.Format("{0}:{1};", u.UserID.ToString(), string.Format("{0} {1}.{2}.", u.Surname, u.Name[0], u.Patro[0]));
                        }
                        this.ViewData["ManagerList"] = s.TrimEnd(';');
                    }
                }

            }
            if (this.ViewData["UserName"] == null)
            {
                this.ViewData["UserName"] = string.Format("{0} {1}.{2}.", CurrentUser.Surname, CurrentUser.Name[0], CurrentUser.Patro[0]);
                if (CurrentUser.IsClient)
                    this.ViewData["ManagerName"] = CurrentUser.ManagerName;
            }
            if (this.ViewData["FinEnable"] == null)
            {                
               this.ViewData["FinEnable"] = CurrentUser.isFinVisible;
            }

        }

        public ActionResult List()
        {
            return View("List");
        }

        public JsonResult OrderDetailsList_json(string sidx, string sord, int page, int rows, bool add)
        {
            int orderid = Convert.ToInt32(this.RouteData.Values["id"]);
            Order o = Repositories.OrderRepository.GetOrder(orderid);
            decimal rate = Repositories.UserRepository.GetUser(o.rf_UserID).Ratio;
            if (add && CurrentUser.IsClient && o.rf_StatusID==1)
            {
                Detail dd = new Detail();
                dd.NameOfGood = "Заполнить";
                dd.PartNumber = "Заполнить";
                dd.rf_OrderID = orderid;
                Repositories.DetailRepository.Add(dd);
                Repositories.DetailRepository.Save();
            }
            List<Detail> dl = Repositories.DetailRepository.GetDetails(orderid).ToList();
            jsModelInstance js = new jsModelInstance(dl.Count, page, rows);
            int manager = !CurrentUser.IsClient ? 0 : 1;
            int fin = CurrentUser.isFinVisible ? 0 : 2;
            int top = (page - 1) * rows;
            if (dl.Count - top < 0)
                js.rows = new jsModelRow[0];
            else
                js.rows = new jsModelRow[dl.Count - top]; 
            for (int i = top; i < dl.Count; i++) 
            {
                js.rows[i - top] = new jsModelRow();
                js.rows[i - top].id = dl[i].DetailID;
                js.rows[i - top].cell = new string[9-manager-fin];
                js.rows[i - top].cell[1] = dl[i].PartNumber;
                js.rows[i - top].cell[2] = dl[i].NameOfGood;
                js.rows[i - top].cell[3] = dl[i].Quantity.ToString();
                js.rows[i - top].cell[4] = dl[i].StartPrice.ToString();
                js.rows[i - top].cell[5 - manager] = dl[i].EndPrice.ToString();
                decimal sum = dl[i].EndPrice*dl[i].Quantity;
                js.rows[i - top].cell[6 - manager] = (sum).ToString();
                if (fin == 0)
                {
                    decimal cred = 0;
                    cred = sum - (dl[i].StartPrice * dl[i].Quantity);
                    js.rows[i - top].cell[7 - manager] = cred.ToString();
                    js.rows[i - top].cell[8 - manager] = (cred * rate).ToString();
                }
            }

            return Json(js, JsonRequestBehavior.AllowGet);   
        }

        
        public JsonResult OrderList_json(string sidx, string sord, int page, int rows)
        {

            List<vOrder> ol;
            if (this.Request.Params["datefrom"] != null)
            {
                DateTime datefrom, dateto;
                DateTime.TryParse(this.Request.Params["datefrom"],out datefrom);
                DateTime.TryParse(this.Request.Params["dateto"],out dateto);
                int userid, managerid;
                Int32.TryParse(this.Request.Params["filclients"], out userid);
                Int32.TryParse(this.Request.Params["filmanagers"], out managerid);
                ol = Repositories.VOrderRepository.GetOrdersOrdered(CurrentUser,datefrom,dateto, userid,managerid).ToList();
            }else
                ol = Repositories.VOrderRepository.GetOrdersOrdered(CurrentUser).ToList();

            jsModelInstance js = new jsModelInstance(ol.Count, page, rows);
            int top = (page - 1) * rows;

            if (ol.Count-top<0)
                js.rows = new jsModelRow[0];
            else
                js.rows = new jsModelRow[ol.Count - top];

            for (int i = top; i < ol.Count; i++)
            {
                decimal rate = Repositories.UserRepository.GetUser(ol[i].UserID).Ratio;
                js.rows[i - top] = new jsModelRow();
                js.rows[i - top].id = ol[i].OrderID;
                js.rows[i - top].cell = new string[9];
                js.rows[i - top].cell[1] = ol[i].OrderID.ToString();
                js.rows[i - top].cell[3] = ol[i].UserName;
                js.rows[i - top].cell[4] = rate.ToString();
                js.rows[i - top].cell[5] = ol[i].OrderSum.ToString();
                js.rows[i - top].cell[6] = ol[i].StatusName;
                Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
                js.rows[i - top].cell[2] = ol[i].OrderDate.ToString("dd/MM/yyyy HH:mm");
                if (ol[i].DeliveryDate.Year == DateTime.MaxValue.Year)
                    js.rows[i - top].cell[7] = "";
                else
                {
                    js.rows[i - top].cell[7] = ol[i].DeliveryDate.ToString("dd/MM/yyyy");
                }
                Thread.CurrentThread.CurrentCulture = new CultureInfo("ru-RU");
                js.rows[i - top].cell[8] = ol[i].IsPaid ? "Оплачено" : "Неоплачено";
            }

            return Json(js, JsonRequestBehavior.AllowGet);        
        }

        public ActionResult OrderListSave(int id, string oper)
        {
            Order o = Repositories.OrderRepository.GetOrder(id);

            User orderuser = Repositories.UserRepository.GetUser(o.rf_UserID);
            if (CurrentUser.IsManager)
            {
                if (orderuser.rf_UserID != CurrentUser.UserID)
                {
                    throw new InvalidOperationException("Заказ принадлежит другому менеджеру");
                }
            }

            if (CurrentUser.IsClient)
            {
                if (o.rf_UserID != CurrentUser.UserID)
                {
                    throw new InvalidOperationException("Заказ принадлежит другому клиенту");
                }
            }
           
            

            if (oper.ToLower() == "del")
            {

                List<Detail> dl = Repositories.DetailRepository.GetDetails(id).ToList();
                foreach (var dtl in dl)
                {
                    Repositories.DetailRepository.Delete(dtl);
                }
                Repositories.DetailRepository.Save();

                Repositories.OrderRepository.Delete(o);
                Repositories.OrderRepository.Save();
            }
            else
            {
                if ((CurrentUser.IsClient) && (o.rf_StatusID > 1))
                {
                        throw new InvalidOperationException("Заказ защищен от изменений");
                }

                if (!CurrentUser.IsClient)
                {
                    if (!string.IsNullOrEmpty(this.Request["datepos"]))
                        o.DeliveryDate = DateTime.Parse(this.Request["datepos"]);
                    o.IsPaid = this.Request["Признак оплаты"].ToLower() == "оплачено";
                }

                o.rf_StatusID = Convert.ToInt32(this.Request["OrderStatus"]);
                if (CurrentUser.IsClient && o.rf_StatusID > 1)
                    MailSender.SendOrder(CurrentUser.ManagerMail,CurrentUser.FIO,o.OrderID.ToString());

                if (!CurrentUser.IsClient)
                    MailSender.SendOrderBack(orderuser.Email, o.OrderID.ToString());

                Repositories.OrderRepository.Save();
            }            
            return new EmptyResult();
        }

        public EmptyResult DetailListSave(int id, string oper)
        {
            Detail d = Repositories.DetailRepository.GetDetail(id);
            Order o = Repositories.OrderRepository.GetOrder(d.rf_OrderID);
            
            if ((o.rf_StatusID > 1)&&(CurrentUser.IsClient))
                throw new InvalidOperationException("Заказ защищен от изменений"); 
    
            if (oper.ToLower() == "del")
            {                           
                Repositories.DetailRepository.Delete(d);
                Repositories.DetailRepository.Save();
            }
            else
            {
                if (CurrentUser.IsClient)
                {
                    d.NameOfGood = this.Request["Наименование"];
                    d.PartNumber = this.Request["P/N"];
                    d.Quantity = Int32.Parse(this.Request["dcount"]);
                }
                else
                {
                    d.StartPrice = Decimal.Parse(this.Request["sPrice"].Replace(".", ","));
                    d.EndPrice = Decimal.Parse(this.Request["ePrice"].Replace(".", ","));
                }
                Repositories.DetailRepository.Save();
            }               
            return new EmptyResult();
        }

        public ActionResult Add()
        {
            if (!CurrentUser.IsClient) 
                return View();
            Order o = new Order();
            o.rf_UserID = CurrentUser.UserID;
            o.rf_StatusID = 1;
            o.OrderDate = DateTime.Now;
            o.DeliveryDate = DateTime.MaxValue;
            Repositories.OrderRepository.Add(o);
            Repositories.OrderRepository.Save();
            return View("List");
        }

        
    }
}
